package cn.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//是否登陆的过滤器
public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("LoginFilter登陆过滤器初始化！");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("登陆拦截开始！");
		HttpServletRequest rq = (HttpServletRequest) request;
		HttpServletResponse rp = (HttpServletResponse) response;
		HttpSession session = rq.getSession();
		Object o = session.getAttribute("USER_LOGIN");
		String path = rq.getRequestURI();// 请求路径
		System.out.println(path);
		String[] msg = { "login", "/js", "/css", "/img", "/excel", "/jquery" };
		for (int i = 0; i < msg.length; i++) {
			if (path.contains(msg[i])) {
				// 执行特殊放行
				chain.doFilter(request, response);
				System.out.println("执行特殊放行");
				break;
			} else if (i == msg.length - 1) {
				// 数组遍历到最后都不是特殊放行
				if (o != null) {
					// 说明已经登陆，可以放行
					chain.doFilter(request, response);
					System.out.println("已登陆放行！");
				} else {
					// 说明没有登陆，重定向到登陆界面
					session.setAttribute("ERROR", "你没有登录！");
					rp.sendRedirect("jsp/login.jsp");
				}
			}
		}
	}

	@Override
	public void destroy() {
		System.out.println("LoginFilter登陆过滤器销毁！");
	}
}
